import React, { Component } from "react";
import { Form, Row, Col, Input, Select, TreeSelect } from "antd";
import { contentSearchFormConfig } from "../../helper/const";
import { getContentCategoryConfig } from "../../helper/service";
import { transformTreeData } from "../../../../helps/utils";
import { addCategoryOpptions } from "../../helper/utils";
const Option = Select.Option;

class SearchForm extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    formFields: contentSearchFormConfig,
  };

  /**
   * 渲染表单项的方法。
   * @param {Array} rowItems - 当前行的所有表单项配置信息。
   * @param {Number} idx - 当前行的索引值。
   * @returns {JSX.Element[]} 返回渲染后的表单项数组。
   */
  renderFormItem(rowItems, idx) {
    const { getFieldDecorator } = this.props.form;
    return rowItems.map((item) => {
      const decorator = getFieldDecorator(item.name, {});
      switch (item.type) {
        case "input":
          return (
            <Col span={8} key={`${idx}-${item.name}`}>
              <Form.Item label={item.label}>{decorator(<Input />)}</Form.Item>
            </Col>
          );

        case "select":
          return (
            <Col span={8} key={`${idx}-${item.name}`}>
              <Form.Item label={item.label}>
                {decorator(
                  <Select
                    placeholder={`请选择${item.label}`}
                    style={{ minWidth: 200, height: 43 }}
                    allowClear
                  >
                    {item.options?.map((option) => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                )}
              </Form.Item>
            </Col>
          );

        case "treeSelect":
          return (
            <Col span={8} key={`${idx}-${item.name}`}>
              <Form.Item label={item.label}>
                {decorator(
                  <TreeSelect
                    style={{ width: "100%", minWidth: 200, height: 43 }}
                    dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                    placeholder="请选择"
                    allowClear
                    treeDefaultExpandAll
                    treeData={item?.options || []}
                    treeCheckable={false} // 单选模式
                  />
                )}
              </Form.Item>
            </Col>
          );

        default:
          return null;
      }
    });
  }

  async componentDidMount() {
    try {
      const response = await getContentCategoryConfig();
      const transformedOptions = response.data
        ? transformTreeData(response.data)
        : [];
      const updatedFields = addCategoryOpptions(
        contentSearchFormConfig,
        transformedOptions
      );
      console.log(updatedFields,32323);
      this.setState({ formFields: updatedFields });
    } catch (error) {
      console.error("获取分类失败:", error);
    }
  }

  render() {
    const { itemsPerRow, onValuesChange } = this.props;
    const { formFields } = this.state;

    const groupedFields = [];
    for (let i = 0; i < formFields.length; i += itemsPerRow) {
      groupedFields.push(formFields.slice(i, i + itemsPerRow));
    }

    return (
      <div className="custom-form">
        <Form layout="inline">
          {formFields.map((rowItems, idx) => (
            <Row key={`row-${idx}`}>{this.renderFormItem(rowItems, idx)}</Row>
          ))}
        </Form>
      </div>
    );
  }
}

const WrappedCustomForm = Form.create({
  onValuesChange: (props, changedValues, allValues) => {
    
    props.onValuesChange(allValues);
  },
})(SearchForm);

export default WrappedCustomForm;
